/*
 * @Date: 2023-03-16 10:15:55
 * @LastEditTime: 2023-03-21 11:05:55
 * @FilePath: /prepaid-refill/src/store/useBalanceStore.ts
 * 介绍:
 */
import { defineStore } from "pinia";
import {
  BbcCoininfo,
  apiBbcCoininfo,
  apiCoinGameBalance,
} from "@@/api/module/balance";

export default defineStore("StoreBalance", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    async getGameBalance(coin: Coin) {
      const res = await apiCoinGameBalance({ coin_id: coin.id });
      if (!res) return;
      const key = coin.code.toUpperCase();
      if (!this.coinEnum[key]) return;
      return (this.coinEnum[key]!.ganmeBalance = Number(res.availbale));
    },
    async getBbcCoininfo() {
      const res = await apiBbcCoininfo();
      if (!res) return;
      this.$patch((state) => {
        state.coinEnum = {
          ...state.coinEnum,
          NAC: { ...state.coinEnum.NAC, ...res },
          USDT: {
            contract_addr: "0x55d398326f99059ff775485246999027b3197955",
            id: 1,
            code: "USDT",
            image: "images/tehter.png",
            logo: "http://solrimage.oss-ap-southeast-1.aliyuncs.com/images/tehter.png",
            format: 18,
            name: "USDT",
            is_withdraw: 0,
            price: 0,
          },
        };
      });
      return this.coinEnum.NAC;
    },
  },
  //*计算属性
  getters: {
    NAC(state) {
      return state.coinEnum.NAC;
    },
    USDT(state) {
      return state.coinEnum.USDT;
    },
  },
  //*仓库数据缓存
  persist: [
    {
      key: "StateBalance",
      storage: localStorage, //指定储存位置
    },
  ],
});
/**state类型定义 */
interface StoreBalance {
  coinEnum: CoinEnum;
}
interface CoinEnum {
  [key: string]: CoinEnumItem | undefined;
  NAC?: CoinEnumItem;
}
type CoinEnumItem = BbcCoininfo.Res | Coin;

/**初始化pinia */
function initState(): StoreBalance {
  return {
    coinEnum: {},
  };
}
